<?php

namespace common\tools;

use Yii;

/**
 * 数组工具类
 */
class ArrayTool
{
    /**
     * 字符串转整形数组
     * @param string $str           字符串
     * @param string $type          类型转换
     * @param string $separator     分隔符
     * @param bool   $filterEmpty   过滤空字符
     * @return array
     */
    public static function strToArray($str, $type = 'int', $separator = ',', $filterEmpty = true)
    {
        $strs = $str ? explode($separator, $str) : [];

        $res = [];
        foreach ($strs as $item) {
            if ($type == 'int') {
                $item = intval($item);
                if ($filterEmpty && $item === 0) continue;
            } elseif ($type == 'string') {
                $item = trim($item);
                if ($filterEmpty && $item === '') continue;
            }
            
            $res[] = $item;
        }
        
        return $res;
    }

}
